<template>
  <div>
    <h2>购物车</h2>
    <ul>
      <li v-for="item in myList" :key="item.id">
        <p>商品</p>
        <p>价格：{{ item.pic }}</p>
        <p>数量：{{ item.number }}</p>
        <input type="button" value="+" @click="add(item)" />
        <input type="button" value="-" @click="sub(item)" />
        <p>小计：{{ item.pic * item.number }}</p>
      </li>
    </ul>
    <div>总价：{{ total }}</div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      myList: [
        { id: 0, number: 0, pic: 10 },
        { id: 2, number: 0, pic: 20 },
        { id: 3, number: 0, pic: 30 },
      ],
      total: 0, // 总价
    };
  },
  created() {
    this.count();
  },
  methods: {
    // 加
    add(item) {
      item.number++;
      this.count();
    },
    // 减
    sub(item) {
      item.number--;
      if (item.number <= 0) {
        return (item.number = 0);
      }
      this.count();
    },
    // 总价：
    count() {
      var totalPic = 0;
      this.myList.forEach((val, index) => {
        this.totalPic += val.number * val.pic;
      });
      this.total = this.totalPic.parseFloat();
    },
  },
};
</script>
